<template>
  <div class="detail-analysis">
    <!-- 标题区域 -->
    <div class="header">
      <h2>Detailed Data Showcase</h2>
      <p class="subtitle">This dashboard page displays the details of the data, providing detailed raw data for finding
        special cases.</p>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm">
        <el-form-item>
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="to"
            start-placeholder="Start Date"
            end-placeholder="End Date"
            style="width: 260px" />
        </el-form-item>

        <el-form-item>
          <el-select
            v-model="filterForm.category"
            placeholder="Product Category"
            clearable
            style="width: 140px">
            <el-option
              v-for="item in filterOptions.categories"
              :key="item"
              :label="item"
              :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            v-model="filterForm.city"
            placeholder="Select City"
            clearable
            style="width: 140px">
            <el-option
              v-for="item in filterOptions.cities"
              :key="item"
              :label="item"
              :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            v-model="filterForm.shopId"
            placeholder="Shop ID"
            clearable
            style="width: 140px">
            <el-option
              v-for="item in filterOptions.shops"
              :key="item"
              :label="`Shop ${item}`"
              :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            v-model="filterForm.gender"
            placeholder="Gender"
            clearable
            style="width: 140px">
            <el-option label="Male" value="male" />
            <el-option label="Female" value="female" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-select
            v-model="filterForm.ageRange"
            placeholder="Age Range"
            clearable
            style="width: 140px">
            <el-option
              v-for="item in filterOptions.ageRanges"
              :key="item"
              :label="item"
              :value="item" />
          </el-select>
        </el-form-item>

        <!-- 利润筛选 -->
        <el-form-item>
          <el-select
            v-model="filterForm.profitOperator"
            placeholder="Profit Comparison"
            clearable
            style="width: 200px">
            <el-option label="=" value="=" />
            <el-option label="<" value="<" />
            <el-option label="<=" value="<=" />
            <el-option label=">" value=">" />
            <el-option label=">=" value=">=" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="filterForm.profitOperator">
          <el-input
            v-model="filterForm.profitAmount"
            placeholder="Please enter the amount"
            style="width: 150px" />
        </el-form-item>

        <!-- 销售额筛选 -->
        <el-form-item>
          <el-select
            v-model="filterForm.salesOperator"
            placeholder="Sales Comparison"
            clearable
            style="width: 200px">
            <el-option label="=" value="=" />
            <el-option label="<" value="<" />
            <el-option label="<=" value="<=" />
            <el-option label=">" value=">" />
            <el-option label=">=" value=">=" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="filterForm.salesOperator">
          <el-input
            v-model="filterForm.salesAmount"
            placeholder="Please enter the amount"
            style="width: 150px" />
        </el-form-item>

        <el-form-item>
          <el-button-group>
            <el-button type="primary" @click="handleSearch">
              <el-icon>
                <Search />
              </el-icon>
              Filter
            </el-button>
            <el-button @click="resetForm">
              <el-icon>
                <Refresh />
              </el-icon>
              Reset
            </el-button>
          </el-button-group>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        :data="tableData"
        style="width: 100%"
        height="calc(100vh - 400px)"
        border
        v-loading="loading">
        <el-table-column prop="shopCode" label="Shop ID" width="100" />
        <el-table-column prop="city" label="City" width="120" />
        <el-table-column prop="channel" label="Channel" width="100" />
        <el-table-column prop="sex" label="Gender" width="80" />
        <el-table-column prop="age" label="Age" width="100" />
        <el-table-column prop="type" label="Product Type" width="120" />
        <el-table-column prop="customNum" label="Customer Number" width="100" />
        <el-table-column prop="price" label="Sales" width="120" />
        <el-table-column prop="orderNum" label="Order Number" width="100" />
        <el-table-column prop="productNum" label="Product Number" width="100" />
        <el-table-column prop="cost" label="Cost" width="120" />
        <el-table-column prop="unitPrice" label="Unit Price" width="120" />
        <el-table-column prop="profit" label="Profit" width="120" />
        <el-table-column prop="createTime" label="Order Date" width="120" />
        <el-table-column prop="week" label="Week" width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { Search, Refresh } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { getFilterOptions, getDetailAnalysis } from '@/api/analysis'
import { ElMessage } from 'element-plus'

// 筛选条件
const filterForm = ref({
  dateRange: [],
  category: '',
  city: '',
  shopId: '',
  gender: '',
  ageRange: '',
  minProfit: null,
  maxProfit: null,
  minSales: null,
  maxSales: null
})

// 筛选选项
const filterOptions = ref({
  categories: [],
  cities: [],
  shops: [],
  genders: [],
  ageRanges: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 获取筛选选项
const fetchFilterOptions = async () => {
  try {
    const options = await getFilterOptions()
    filterOptions.value = options
  } catch (error) {
    console.error('获取筛选选项失败:', error)
    ElMessage.error('获取筛选选项失败')
  }
}

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true
  try {
    const params = {
      ...filterForm.value,
      userId: JSON.parse(localStorage.getItem('userInfo'))?.id,
      startDate: filterForm.value.dateRange[0],
      endDate: filterForm.value.dateRange[1],
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    const { records, total: totalCount } = await getDetailAnalysis(params)
    tableData.value = records
    total.value = totalCount
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  currentPage.value = 1
  fetchTableData()
}

// 重置表单
const resetForm = () => {
  filterForm.value = {
    dateRange: [],
    category: '',
    city: '',
    shopId: '',
    gender: '',
    ageRange: '',
    minProfit: null,
    maxProfit: null,
    minSales: null,
    maxSales: null
  }
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTableData()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTableData()
}

onMounted(() => {
  fetchFilterOptions()
  fetchTableData()
})
</script>

<style scoped>
.detail-analysis {
  width: calc(100vw - 400px);
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.header {
  padding: 24px;
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
}

.header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #1f2f3d;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 14px;
  color: #5e6d82;
  margin: 0;
}

.filter-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin: 24px;
  margin-bottom: 20px;
}

.filter-section :deep(.el-form--inline) {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-section :deep(.el-form-item) {
  margin-right: 0;
  margin-bottom: 12px;
}

.filter-section :deep(.el-select) {
  width: 140px;
}

.separator {
  margin: 0 8px;
  color: #999;
}

.table-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  margin: 0 24px;
}

.table-section :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.table-section :deep(.el-table th) {
  background-color: #f5f7fa;
  color: #1f2f3d;
  font-weight: 600;
}

.table-section :deep(.el-table td) {
  color: #5e6d82;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card) {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

:deep(.el-card:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-input-number) {
  width: 130px !important;
}

:deep(.el-date-editor) {
  width: 260px !important;
}

:deep(.el-button) {
  padding: 8px 16px;
  font-weight: 500;
}

:deep(.el-button--primary) {
  background-color: #409EFF;
}

:deep(.el-pagination) {
  padding: 0;
  font-weight: normal;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
  border-radius: 8px;
}
</style>